package com.kevin.handler;

import com.kevin.constant.ReqType;
import com.kevin.core.Header;
import com.kevin.core.RpcProtocol;
import com.kevin.core.RpcRequest;
import com.kevin.core.RpcResponse;
import com.kevin.spring.SpringBeanManager;
import com.kevin.spring.service.HandlerMapping;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

public class RpcServerHandler extends SimpleChannelInboundHandler<RpcProtocol<RpcRequest>> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcProtocol<RpcRequest> rpcRequestRpcProtocol) throws Exception {

        System.out.println("进入RpcServerHandler");
        RpcProtocol<RpcResponse> responseRpcProtocol = new RpcProtocol<>();
        RpcResponse rpcResponse = new RpcResponse();
        Header header = rpcRequestRpcProtocol.getHeader();
        header.setReqType(ReqType.REQ_RESPONSE.getCode());
        RpcRequest rpcRequest = rpcRequestRpcProtocol.getContent();
        System.out.println("进入RpcServerHandler rpcRequest ："+rpcRequest.toString());
        rpcResponse.setMsg("success");
        rpcResponse.setData(invoke(rpcRequest));
        responseRpcProtocol.setHeader(header);
        responseRpcProtocol.setContent(rpcResponse);
        channelHandlerContext.writeAndFlush(responseRpcProtocol);
    }

    /**
     * 不集成到springboot实现
     * @param rpcRequest
     * @return
     */
//    private Object invoke(RpcRequest rpcRequest) {
//        try {
//            Class clazz = Class.forName(rpcRequest.getClassName());
//            Object bean = SpringBeanManager.getBean(clazz);
//            Method method = clazz.getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
//            return method.invoke(bean, rpcRequest.getParams());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    private Object invoke(RpcRequest rpcRequest) {
        try {
            return HandlerMapping.getInstance().invoke(rpcRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
